package com.zj.cman.handlers;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.zj.cman.constants.TABLES_CONSTANT;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.sql.Timestamp;
import java.time.LocalDateTime;

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    private static final String FIELD_NAME_STATUS = "status";
    private static final String USER_FIELD_STATUS_DEF_VAL = "inactive";

    private static final String FIELD_NAME_CREATED_TIME = "createdTime";
    private static final String FIELD_NAME_UPDATED_TIME = "createdTime";

    private static final String META_NAME_TABLE = "table";


    @Override
    public void insertFill(MetaObject metaObject) {
        String tableName = getTableName(metaObject); // 获取当前操作的表名

        this.strictInsertFill(metaObject, FIELD_NAME_CREATED_TIME, Timestamp.class, Timestamp.valueOf(LocalDateTime.now()));
        if(TABLES_CONSTANT.USERS.equals(tableName)){
            this.strictInsertFill(metaObject, FIELD_NAME_STATUS, String.class, USER_FIELD_STATUS_DEF_VAL);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.strictUpdateFill(metaObject, FIELD_NAME_UPDATED_TIME, Timestamp.class, Timestamp.valueOf(LocalDateTime.now()));
    }

    private String getTableName(MetaObject metaObject) {
        // 实现获取表名的逻辑，可以基于实体类名或其他信息
        // 这里只是一个示例，具体实现取决于你的项目结构
        return metaObject.getValue(META_NAME_TABLE).toString();
    }
}
